package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.DownloadListener;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.example.library.utils.StringUtils;

public class WebviewActivity extends AppCompatActivity {

    private LinearLayout ll_view;

    //网页地址
    private String webUrl = "https://kefu.easemob.com/webim/im.html?configId=982d8f2d-06db-49ab-9e14-673c151172b6";
    //网页标题
    private String webTile = "";
    private WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        ll_view = findViewById(R.id.ll_view);

//        if (!StringUtils.isBlank(getIntent().getStringExtra("web_url"))) {
//            webUrl = getIntent().getStringExtra("web_url");
//        }
//        if (!StringUtils.isBlank(getIntent().getStringExtra("web_url"))) {
//            webTile = getIntent().getStringExtra("web_url");
//        }
        webview = new WebView(this);
        webview.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        ll_view.addView(webview);

        WebSettings setting = webview.getSettings();
        //解决https链接重定向时候无法访问问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //重写一下。有的时候可能会出现问题
        webview.setWebChromeClient(new myWebChromeClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        setting.setJavaScriptEnabled(true);
        setting.setDefaultTextEncodingName("UTF-8");
        setting.setUseWideViewPort(true);
        setting.setLoadWithOverviewMode(true);
        setting.setDomStorageEnabled(true);
//        setting.setAppCacheMaxSize(1024 * 1024 * 8);
//        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
//        setting.setAppCachePath(appCachePath);
        setting.setAllowFileAccess(true);
        setting.setAppCacheEnabled(true);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            setting.setAllowFileAccessFromFileURLs(true);
            setting.setAllowUniversalAccessFromFileURLs(true);
        }
        // 支持下载
        webview.setDownloadListener(new MyWebViewDownLoadListener());
        // 设置Web视图
        webview.setWebViewClient(new myWebViewClient());


        if (!StringUtils.isBlank(webUrl)) {
            webview.loadUrl(webUrl);
        } else {
            webview.loadUrl("http://pp.zhifa120.cn");
        }
    }

    //h5请求顶部显示
    private class myWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
//            if (StringUtils.isBlank(webTile)) {
//                if (!StringUtils.isBlank(title)) {
//                    tvTitle.setText(title);
//                } else {
//                    tvTitle.setText(webUrl);
//                }
//            } else {
//                tvTitle.setText(webTile);
//            }
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            super.onPermissionRequest(request);
            WebviewActivity.this.runOnUiThread(new Runnable(){
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    request.grant(request.getResources());
                }
            });
        }
    }

    /**
     * 支持下载
     */
    private class MyWebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    private class myWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            ViewParent parent = webview.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webview);
            }
            webview.stopLoading();
            webview.getSettings().setJavaScriptEnabled(false);
            webview.clearHistory();
            webview.removeAllViews();
            webview.destroy();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}